import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Icon, Input, message, Tag, Form, DatePicker, Select, Table, Pagination } from "antd";
import MarkdownEditor from "@/utils/vditorContent";
import { formatMessage } from "umi-plugin-react/locale";
import {
  agreementCommentEdit,
  agreementList,
  agreementRelease,
  editUpdateAgreement,
  getAgreementInfo,
  privacyAgreementList,
  userAgreementList,
} from "@/services/platformManagement";
import moment from "moment";

class AgreementInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      current: 1,
      size: 10,
      total: 0,
      loading: false,
      list: [],
      pathname: "",
    };
  }

  componentDidMount() {
    const {
      location: { pathname },
    } = this.props;
    this.setState({ pathname }, () => {
      this.getList();
    });
  }

  getList = () => {
    this.setState(
      {
        loading: true,
      },
      async () => {
        const { pathname, current, size } = this.state;
        const {
          form: { getFieldsValue },
        } = this.props;
        let obj = {
          current,
          size,
          startTime: getFieldsValue().time && getFieldsValue().time[0] ? moment(getFieldsValue().time[0]).format("YYYY-MM-DD HH:mm:ss") : "",
          endTime: getFieldsValue().time && getFieldsValue().time[1] ? moment(getFieldsValue().time[1]).format("YYYY-MM-DD HH:mm:ss") : "",
          version: getFieldsValue().search,
          status: getFieldsValue().status == -1 ? null : getFieldsValue().status,
          type: pathname.indexOf("userAgreement") != -1 ? 0 : 1,
        };
        let res = await agreementList(obj);
        this.setState({ loading: false, list: res.records, total: res.total });
      }
    );
  };

  doSearch = (current, size) => {
    this.setState({ current, size }, () => {
      this.getList();
    });
  };

  toDetail = (id) => {
    const {
      history,
      location: { pathname },
    } = this.props;
    let url = pathname.indexOf("userAgreement") != -1 ? "/agreementInfo/userAgreement/signDetails" : "/agreementInfo/privacyAgreement/signDetails";
    history.push({ pathname: url, query: { id, pathname } });
  };

  toEdit = (id, editType) => {
    const {
      history,
      location: { pathname },
    } = this.props;
    let url = pathname.indexOf("userAgreement") != -1 ? "/agreementInfo/userAgreement/edit" : "/agreementInfo/privacyAgreement/edit";
    history.push({ pathname: url, query: { id, pathname, editType, type: pathname.indexOf("userAgreement") != -1 ? 0 : 1 } });
  };

  doRelease = async (id) => {
    const res = await agreementRelease({ id });
    if (res.code != -1) {
      message.info(res.message);
    }
    this.getList();
  };

  doSaveComment = async (e, row, index) => {
    const res = await agreementCommentEdit({ id: row.id, comment: e.target.value });
    message.info(res.message);
    this.getList();
  };

  dbClickCell = (index) => {
    console.log(1111);
    const { list } = this.state;
    list[index].isEdit = true;
    this.setState({
      list,
    });
  };

  render() {
    const { current, size, total, list, loading } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const columns = [
      {
        title: formatMessage({ id: "platformManagement.agreementInfo.version" }),
        dataIndex: "version",
        width: 150,
        render: (version, row) => {
          return row.activeTime ? moment(row.activeTime).format("YYYY-MM-DD HH:mm") : "";
        },
      },
      {
        title: formatMessage({ id: "platformManagement.agreementInfo.createTime" }),
        dataIndex: "createTime",
        width: 200,
        render: (time) => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : "";
        },
      },
      {
        title: formatMessage({ id: "platformManagement.agreementInfo.activeTime" }),
        dataIndex: "activeTime",
        width: 200,
        render: (time) => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm") : "";
        },
      },
      {
        title: formatMessage({ id: "platformManagement.agreementInfo.signCount" }),
        dataIndex: "times",
        width: 100,
      },
      {
        title: formatMessage({ id: "platformManagement.agreementInfo.status" }),
        dataIndex: "status",
        width: 100,
        render: (status) => {
          return status == 0 ? formatMessage({ id: "platformManagement.agreementInfo.statusEditing" }) : "";
        },
      },
      {
        title: formatMessage({ id: "platformManagement.agreementInfo.remarks" }),
        dataIndex: "comment",
        width: 200,
        render: (comment, row, index) => {
          return (
            <div style={{ minHeight: 35 }}>
              {row.isEdit ? (
                <Input.TextArea defaultValue={row.comment} onBlur={(e) => this.doSaveComment(e, row, index)} />
              ) : (
                <div onDoubleClick={() => this.dbClickCell(index)} style={{ minHeight: 35 }}>
                  {row.comment}
                </div>
              )}
            </div>
          );
        },
      },
      {
        title: formatMessage({ id: "platformManagement.agreementInfo.actions" }),
        width: 250,
        render: (text, row, index) => {
          return row.status == 0 ? (
            <div>
              <Button style={{ marginRight: 8 }} onClick={() => this.doRelease(row.id)}>
                {formatMessage({ id: "platformManagement.agreementInfo.switchToActive" })}
              </Button>
              <Button type="primary" onClick={() => this.toEdit(row.id, "edit")}>
                {formatMessage({ id: "platformManagement.agreementInfo.edit" })}
              </Button>
            </div>
          ) : (
            <div>
              <Button type="primary" style={{ marginRight: 8 }} onClick={() => this.toDetail(row.id)}>
                {formatMessage({ id: "platformManagement.agreementInfo.viewSignDetails" })}
              </Button>
              <Button type="primary" onClick={() => this.toEdit(row.id, "view")}>
                {formatMessage({ id: "platformManagement.agreementInfo.view" })}
              </Button>
            </div>
          );
        },
      },
    ];

    return (
      <div style={{ height: "100%", padding: 24, background: "#ffffff", overflowY: "auto" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
          <Form layout="inline">
            <Form.Item>{getFieldDecorator("time")(<DatePicker.RangePicker style={{ width: 220 }} />)}</Form.Item>
            <Form.Item>
              {getFieldDecorator("status", { initialValue: -1 })(
                <Select style={{ width: 150 }}>
                  <Select.Option value={-1}>{formatMessage({ id: "platformManagement.agreementInfo.all" })}</Select.Option>
                  <Select.Option value={2}>{formatMessage({ id: "platformManagement.agreementInfo.statusHistorical" })}</Select.Option>
                  <Select.Option value={1}>{formatMessage({ id: "platformManagement.agreementInfo.statusActive" })}</Select.Option>
                  <Select.Option value={0}>{formatMessage({ id: "platformManagement.agreementInfo.statusEditing" })}</Select.Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator("search", { initialValue: "" })(
                <Input.Search
                  placeholder={formatMessage({ id: "platformManagement.agreementInfo.searchPlaceholder" })}
                  onSearch={() => this.doSearch(1, size)}
                />
              )}
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={() => this.doSearch(1, size)}>
                {formatMessage({ id: "platformManagement.agreementInfo.search" })}
              </Button>
            </Form.Item>
          </Form>
          <Button type="primary" onClick={() => this.toEdit(null, "add")}>
            {formatMessage({ id: "platformManagement.agreementInfo.newAgreement" })}
          </Button>
        </div>
        <Table columns={columns} dataSource={list} loading={loading} rowKey={"id"} pagination={false} scroll={{ x: "auto" }} />
        {total > 10 ? (
          <Pagination
            style={{ textAlign: "right", marginTop: 16 }}
            total={total}
            current={current}
            pageSize={size}
            showQuickJumper={true}
            showSizeChanger={true}
            onChange={this.doSearch}
            onShowSizeChange={this.doSearch}
          />
        ) : null}
      </div>
    );
  }
}

export default Form.create()(AgreementInfo);
